package exer;

/**
 * @Author 不知名网友鑫
 * @Date 2022/5/5
 * 生产者(Productor)将产品交给店员(Clerk)，而消费者(Customer)从店员处取走产品，
 * 店员一次只能持有固定数量的产品(比如:20），如果生产者试图生产更多的产品，店员
 * 会叫生产者停一下，如果店中有空位放产品了再通知生产者继续生产；如果店中没有产品
 * 了，店员会告诉消费者等一下，如果店中有产品了再通知消费者来取走产品。
 **/
public class Exer2 {
    public static void main(String[] args) {
        Clerk clerk = new Clerk(0);
        Productor productor = new Productor(clerk);
        Customer customer = new Customer(clerk);
        productor.setName("生产者");
        customer.setName("消费者");
        productor.start();
        customer.start();
    }
}
//生产者线程
class Productor extends Thread{
    private Clerk clerk =new Clerk(0);
    public Productor(Clerk clerk) {
        this.clerk=clerk;
    }

    @Override
    public void run() {
        while(true) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            clerk.add();
        }
    }
}
//消费者线程
class Customer extends Thread{
    private Clerk clerk = new Clerk(0);

    public Customer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while(true) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            clerk.reduce();
        }
    }
}
class Clerk{
    private int iphoneCount=0;

    public Clerk(int iphoneCount) {
        this.iphoneCount = iphoneCount;
    }

    public synchronized void reduce() {
        //当产品大于0时，可以消费
        if(iphoneCount>0){
            System.out.println(Thread.currentThread().getName()+"消费了第"+iphoneCount+"个");
            iphoneCount--;
            //释放生产者的wait的线程。提示可以生产
            notify();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }

    public synchronized void add() {
        //当库存小于20时，继续生产
        if(iphoneCount<20){
            iphoneCount++;
            System.out.println(Thread.currentThread().getName()+"生产了第"+iphoneCount+"个");
            //释放消费者的wait的线程。提示可以消费
            notify();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
